import axios, { AxiosInstance, AxiosRequestConfig, AxiosResponse } from "axios";
import querystring from 'querystring';
import { resData } from "./interface";
import { ElMessage } from "element-plus";
import router from '@/router';

let baseUrl = '/api';
let config = {

}

class HttpRequest {
    http: AxiosInstance
    constructor(config: AxiosRequestConfig) {
        this.http = axios.create(config);
        this.http.interceptors.request.use(req => {
            let userInfo: any = sessionStorage.getItem('userInfo');
            req.headers.authorization = userInfo ? JSON.parse(userInfo).token : null;
            return req;
        });
        this.http.interceptors.response.use((res: AxiosResponse): any => {
            if (res.data.code == 403) {
                ElMessage.warning('登录已过期');
                router.push('/login');
            }
            // if (res.data.msg[0] == '请设置请求头,并携带验证字符串') {
            //     ElMessage.warning(res.data.msg);
            //     router.push('/login');
            // }
            return res.data;
        });
    }
    get<T>(url: string, params?: any): Promise<resData<T>> {
        return this.http.get(baseUrl + url, {
            params
        })
    }
    post<T>(url: String, params?: any, isfile: Boolean = false): Promise<resData<T>> {
        let data: any = null;
        if (isfile) {
            data = new FormData();
            for (let [key, val] of Object.entries(params)) {
                data.append(key, val)
            }
        } else {
            data = querystring.stringify(params);
        }
        return this.http.post(baseUrl + url, params);
    }
}

export default new HttpRequest(config);